package com.li.mybatisconfig.proxy;

import com.li.mybatisconfig.bean.Function;
import com.li.mybatisconfig.bean.MapperBean;
import com.li.mybatisconfig.config.MyConfiguration;
import com.li.mybatisconfig.config.MysqlSession;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @Description：
 * @Author：LiDong
 * @Create：2020/9/2
 * @Version：1.0.0
 */
public class MyMapperProxy implements InvocationHandler {

    private MysqlSession mysqlSession;
    private MyConfiguration myConfiguration;


    public MyMapperProxy(MysqlSession mysqlSession, MyConfiguration myConfiguration) {
        this.mysqlSession = mysqlSession;
        this.myConfiguration = myConfiguration;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperBean mapperBean = myConfiguration.readMapper("UserMapper.xml");
        // 判断是否是xml文件对应的接口
        if (!method.getDeclaringClass().getName().equals(mapperBean.getInterfaceName())) {
            return null;
        }
        List<Function> list = mapperBean.getList();
        if (!CollectionUtils.isEmpty(list)) {
            for (Function x : list) {
                if (judge(method, x, "selectById")) {
                    return mysqlSession.selectOne(x.getSql(), String.valueOf(args[0]));
                }
                if (judge(method, x, "deleteById")) {
                    mysqlSession.deleteOne(x.getSql(), String.valueOf(args[0]));
                }
                if (judge(method, x, "insert")) {
                    mysqlSession.insertOne(x.getSql(), String.valueOf(args[0]));
                }
                if (judge(method, x, "updateById")) {
                    mysqlSession.updateOne(x.getSql(), String.valueOf(args[0]));
                }
            }
        }
        return null;
    }


    /**
     * 判断Mapper文件中id是否一致
     */
    private boolean judge(Method method, Function x, String methodId) {
        return method.getName().equals(x.getFunctionName()) && x.getFunctionName().equals(methodId);
    }
}